document.addEventListener('DOMContentLoaded', function() {
    // 查找按钮点击事件
    document.getElementById('findBtn').addEventListener('click', function() {
        // 获取查询类型（类名或ID）
        const queryType = document.querySelector('input[name="queryType"]:checked').value;
        const queryValue = document.getElementById('queryValue').value.trim();
        const resultsDiv = document.getElementById('results');
        resultsDiv.innerHTML = '';

        if (!queryValue) {
            resultsDiv.innerHTML = '<div class="error">请输入查询值</div>';
            return;
        }

        // 向当前活动标签页注入脚本
        chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
            chrome.scripting.executeScript({
                target: { tabId: tabs[0].id },
                func: function(type, value) {
                    // 辅助函数：获取元素的各种位置信息
                    function getElementPositions(element) {
                        // 1. 相对于视口的位置
                        const viewportRect = element.getBoundingClientRect();

                        // 2. 相对于文档的位置（考虑滚动）
                        const docRect = {
                            top: viewportRect.top + window.pageYOffset,
                            left: viewportRect.left + window.pageXOffset,
                            bottom: viewportRect.bottom + window.pageYOffset,
                            right: viewportRect.right + window.pageXOffset,
                            width: viewportRect.width,
                            height: viewportRect.height
                        };

                        // 3. 相对于屏幕的位置
                        // 获取浏览器窗口在屏幕上的位置
                        const screenX = window.screenX || window.screenLeft;
                        const screenY = window.screenY || window.screenTop;

                        // 计算浏览器工具栏高度
                        const toolbarHeight = screenY + (window.outerHeight - window.innerHeight) -
                            (window.scrollY > 0 ? 0 : window.scrollY);

                        const screenRect = {
                            top: Math.round(screenY + toolbarHeight + viewportRect.top),
                            left: Math.round(screenX + viewportRect.left),
                            bottom: Math.round(screenY + toolbarHeight + viewportRect.bottom),
                            right: Math.round(screenX + viewportRect.right),
                            width: Math.round(viewportRect.width),
                            height: Math.round(viewportRect.height)
                        };

                        // 4. 元素的其他属性
                        const offsetParent = element.offsetParent ? element.offsetParent.tagName : '无';

                        return {
                            viewport: {
                                top: Math.round(viewportRect.top),
                                left: Math.round(viewportRect.left),
                                bottom: Math.round(viewportRect.bottom),
                                right: Math.round(viewportRect.right),
                                width: Math.round(viewportRect.width),
                                height: Math.round(viewportRect.height)
                            },
                            document: {
                                top: Math.round(docRect.top),
                                left: Math.round(docRect.left),
                                bottom: Math.round(docRect.bottom),
                                right: Math.round(docRect.right),
                                width: Math.round(docRect.width),
                                height: Math.round(docRect.height)
                            },
                            screen: screenRect,
                            offsetParent: offsetParent,
                            offset: {
                                top: Math.round(element.offsetTop),
                                left: Math.round(element.offsetLeft)
                            }
                        };
                    }

                    // 根据查询类型处理
                    if (type === 'class') {
                        // 按类名查询
                        const elements = document.getElementsByClassName(value);
                        if (elements.length === 0) {
                            return { error: `未找到类名为 "${value}" 的元素` };
                        }

                        const results = [];
                        for (let i = 0; i < elements.length; i++) {
                            results.push({
                                index: i,
                                tagName: elements[i].tagName,
                                positions: getElementPositions(elements[i])
                            });
                        }
                        return { results, type: 'class', value: value };
                    } else {
                        // 按ID查询
                        const element = document.getElementById(value);
                        if (!element) {
                            return { error: `未找到ID为 "${value}" 的元素` };
                        }

                        return {
                            results: [{
                                tagName: element.tagName,
                                positions: getElementPositions(element)
                            }],
                            type: 'id',
                            value: value
                        };
                    }
                },
                args: [queryType, queryValue]
            }, function(injectionResults) {
                if (!injectionResults || !injectionResults[0]) {
                    resultsDiv.innerHTML = '<div class="error">获取信息失败</div>';
                    return;
                }

                const result = injectionResults[0].result;
                if (result.error) {
                    resultsDiv.innerHTML = `<div class="error">${result.error}</div>`;
                } else if (result.results) {
                    const typeText = result.type === 'class' ? '类名' : 'ID';
                    resultsDiv.innerHTML = `<p>找到 ${result.results.length} 个${typeText}为"${result.value}"的元素：</p>`;

                    result.results.forEach(function(item, index) {
                        const itemDiv = document.createElement('div');
                        itemDiv.className = 'result-item';

                        let indexText = '';
                        if (result.type === 'class') {
                            indexText = `#${item.index} `;
                        }

                        // 构建三种位置信息的HTML
                        itemDiv.innerHTML = `
                            <strong>元素 ${indexText}(${item.tagName})</strong>
                            
                            <div class="section-title">相对于视口 (Viewport)</div>
                            <div class="position-group">
                                顶部: ${item.positions.viewport.top}px, 左侧: ${item.positions.viewport.left}px<br>
                                底部: ${item.positions.viewport.bottom}px, 右侧: ${item.positions.viewport.right}px<br>
                                宽度: ${item.positions.viewport.width}px, 高度: ${item.positions.viewport.height}px
                            </div>
                            
                            <div class="section-title">相对于文档 (Document)</div>
                            <div class="position-group">
                                顶部: ${item.positions.document.top}px, 左侧: ${item.positions.document.left}px<br>
                                底部: ${item.positions.document.bottom}px, 右侧: ${item.positions.document.right}px<br>
                                宽度: ${item.positions.document.width}px, 高度: ${item.positions.document.height}px
                            </div>
                            
                            <div class="section-title">相对于屏幕 (Screen)</div>
                            <div class="position-group">
                                顶部: ${item.positions.screen.top}px, 左侧: ${item.positions.screen.left}px<br>
                                底部: ${item.positions.screen.bottom}px, 右侧: ${item.positions.screen.right}px<br>
                                宽度: ${item.positions.screen.width}px, 高度: ${item.positions.screen.height}px
                            </div>
                            
                            <div class="section-title">其他位置信息</div>
                            <div class="position-group">
                                偏移父元素: ${item.positions.offsetParent}<br>
                                相对于偏移父元素 - 顶部: ${item.positions.offset.top}px, 左侧: ${item.positions.offset.left}px
                            </div>
                        `;
                        resultsDiv.appendChild(itemDiv);
                    });
                }
            });
        });
    });

    // 支持回车键触发查找
    document.getElementById('queryValue').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            document.getElementById('findBtn').click();
        }
    });
});